var deal_product = 'hot';
//var capital_one = 'XAUUSD';
var data_setInt = 0;
var data_setInt_option = 0;
var default_order = 10;//下单默认金额
var order_dirt = 0; //0看涨1看空
var deal_time = 0;//到期时间
var time_limit = 0;
var inteval_time = 1000;
var diff_one = 1; //1min 5min 5min 60min
var chgsta = 0;   //记录循环的变量
var times = '60';
var timer_countDown = null;
var new_order_id = 0;
var new_order_price = 0;
var e_price = 0;
var fate = 0;
var e_is = 0;
var shifoukaishi = 0;
window.ed = 0;
var rsecond=0;
//var changerate = 1;
var changerate = 6.6733*10;
/**
 * Created by zeteng on 2017/6/19.
 */


function set_profit(valu_t) {
    if (valu_t == 60) {
        return 0.8;
    } else if (valu_t == 120) {
        return 0.83;
    } else if (valu_t == 150) {
        return 0.86;
    }
}

Zepto(function(){
    //头像宽高等比
    var pic_w = $(".index_content header dt img").width();
    $(".index_content header dt img").height(pic_w);
    //开始游戏点击按钮
    var window_h = $(window).height();
    $(".index_data").css({"minHeight":window_h});
    $(".index_list ul li").on('touchend',function(){
        var index = $(this).index();

        $(".index_data").eq(index).css({"display":"block"}).siblings(".index_data").css({"display":"none"});
        $(this).addClass("current").siblings().removeClass("current");


        if( index == 2 )
        {
            //获得最近成交的10条记录
            //alert("最近已经成交的订单");
            load_now(1, 15, 1, "/Wap/Trading/get_now_orders");
        }else if( index == 1 )
        {
            load_now2(1, 15, 1, "/Wap/Trading/get_open_orders");
        }
    });

    $(".index_data:last-child ol").height(0);
    $(".chi_c>p:nth-of-type(2)").css({"display":"none"});
    $(".chi_c>p:nth-of-type(3)").css({"display":"none"});



    $(".goods ul li,.kxt_btn ul li").on('touchend',function(e){
        $(this).siblings().removeClass("current");
        $(this).addClass('current');
        if($(this).parent().parent().prop('class')=='kxt_btn'){

            showType = $(this).data('src');
        }else{
            $("#cur_show_good").val($(this).data('src'));

        }
        myChart.showLoading({text:'',textColor:'#9b9b9b',color:'#444',maskColor:'rgba(0, 0, 0, 0.2)'});

        if( $("#cur_show_good").val() == "BTbtccny" ) {
            if( showType > 0 ){
                doSend("{'event':'addChannel','channel':'ok_sub_spotcny_btc_kline_" + showType + "min'}");
            }else if( showType == 0 ){
                getbtcminmin();
            }
        }else if( $("#cur_show_good").val() == "NECLA0" ){
            if( showType > 0 )
            {
                $.ajax({
                    type: "POST",
                    url: "/Wap/Trading/goldchartdata1",
                    data:"type="+showType,
                    datatype: 'JSON',
                    success: function (response) {
                        var array = JSON.parse(response);
                       processDataChild( array, "K" );
                    },
                    error: function () {
                    },
                    complete: function () {
                        //hideLoading()
                    }
                    //  "json");
                });
            }else if( showType == 0 ){
                getgoldminmin();
            }
        }




    });
    if(localStorage.getItem("_teaching")==undefined && $("#userid").val()!='') {
        localStorage.setItem("_teaching", '1');
        novice();
    }

    /*签到按钮*/
    $("#_sign_dt").click(function(){
        check_login(function () {
            $("#_sign_dt").hide();
            _Toast('今日签到完成');
        });
        return false;
    });



    /*确认购买按钮*/
    $("#buybtn").on("click", function () {

        if (!$("#flow_span_value").text()) {
            return false;
        }

        $('#buildBox').hide();
        $("#daoqi").hide();
        $("#dangqian").show();
        $("#flow_span_value2").show();
        $("#flow_span_value3").hide();
        $("#buy_price").text();
        //$("#fnTimeCountDown").html('<span class="sec">59</span>');


        deal_ajax(order_dirt);
        //show_date_time(60);
    });


    $("#setting").on("click", function () {

        clearInterval(timer_countDown);
        $('#buildBox').hide();
        $('#buildConfirm').hide();
        pop_Close();
        var type = $("#time_diff a.changed").attr("type");
        var diff = type * 60;
        //clearInterval(window.param[getCapitalTypeById("sw_active")+diff]);
        //console.log(getCapitalTypeById("sw_active") + diff);
        //setTimeout(function () {drawKline_end(getCapitalTypeById("sw_active"), getDiffById("time_diff"), "svgId", "", "deal_value");}, 2000);//yang
        buycomplete();
        $("#js_alert_result").addClass("none").removeClass("red").removeClass("green").removeClass("gray");
        // $("#js-alert-box").removeClass("none");
        // $("#js-alert-box").removeClass("showblock");

    });
});



//下单发送ajax
function deal_ajax(dirc) {

    var deal_amount; //下单金额
    var captial; //资产种类
    var captial_id;
    var product; //资产
    var finish_time; //到期时间
    var dircetion; //方向
    var deal_value; //下单点位
    var yield; //收益率
    var expect_profit; //收益值
    var faild_profit; //保底值
    var msg;
    //获取收益率
    times = $(".swiper-slide-active").find(".digspan").html();
    times = times.replace(" ", "");
    times = parseInt(times);
    var yield = set_profit(times);
    //expect_profit = $("#winner_rate").html();
    //expect_profit = expect_profit.replace("￥", ""); //去除￥
    faild_profit = $("#failer_rate").html();
    //faild_profit = faild_profit.replace("￥", ""); //去除￥
    var deal_amount = $(".slct p i").text();
    if (deal_amount == '') {
        deal_amount = $("#input_money").val();
    }
    if (!deal_amount) {
        deal_amount = default_order;
    } else if (deal_amount < default_order) { //最低下单金额限制
        showLoading('下单金额过低，无法交易！', 2000);
        pop_Close();
        return 0;
    }

    //expect_profit = deal_amount * (1 + WINNERT);
    expect_profit = deal_amount * (1 + yield);
    captial = get_cap_key();

    //deal_value = $("#nowpotis").text();
    deal_value = $("#flow_span_value").text();

    positi = deal_value.indexOf("元");
    if( positi > 0 ){
        deal_value = deal_value.substring( 0, positi );
    }

    finish_time = $("#flow_span_time").text();
    deal_time = parseInt(finish_time);
    jQuery.ajax({
        type: 'post',
        url: ROOT + "/Wap/Trading/deal_dq",
        data: "amount=" + deal_amount + "&trade_time=" + deal_time + "&capital=" + captial + "&product=" + deal_product + "&dircetion=" + dirc + "&sec=" + finish_time + "&deal_value=" + deal_value + "&yield=" + yield +"&expect_profit=" + expect_profit + "&faild_profit=" + faild_profit,
        dataType: 'JSON',
        async: true,
        //timeout: 900,
        error: function (data) {
            alert("下单失败");
            //showLoading('下单失败！', 2000);
            pop_Close();
            return 0;
        },
        success: function (data_t) {
            //var json_data = eval('(' + data_t + ')');
            var json_data = eval(data_t);
            if (json_data['type'] == 'success') {
                new_order_id = json_data['id'];
                var deal_value = json_data['deal_value'];

                $("#buy_price").text(deal_value);
                new_order_price = deal_value;
                if (json_data['direction'] == 0) {
                    $("#flow_span_dir1").html('<font color="green">买跌</font>');
                } else {
                    $("#flow_span_dir1").html('<font color="red">买涨</font>');
                }
                $('#buildConfirm').show();
                var now_time = new Date().getTime();
                var daoqi_time = deal_time * 1000 * 60;
                var endTime = parseInt(now_time) + parseInt(daoqi_time);
                $('.sec').text(deal_time);
                $("#js-sec-text").html (deal_time);
                var e = Math.round( deal_time/deal_time * 570.846 );
                document.getElementById("js-sec-circle").style.strokeDashoffset = e-570.846;
                $("#js-alert-box").addClass("showblock");



                clearInterval(timer_countDown);
                timer_countDown = setInterval('countDown(' + endTime + ',' + deal_time + ')', 500);
                $("#money").html(json_data['usermoney']);
                $("#minijin").html(json_data['sim_money']);
                var dot_len = get_data_space(captial);
                e_price = parseFloat(json_data['e_price']).toFixed(dot_len);
                fate = parseFloat(json_data['fate']).toFixed(dot_len);
                e_is = json_data['e_is'];
                //$("#money").text(parseFloat($("#money").text())-parseFloat(deal_amount));
                //$("#minijin").text(parseFloat($("#minijin").text())-parseFloat(deal_amount));
                load_now2(1, 15, 1, "/Wap/Trading/get_open_orders");
            } else if (json_data['type'] == 'error') {
                //alert(json_data['error']);
                alert( json_data['error'] );
                showLoading(json_data['error'], 2000);
                pop_Close();
            }
            return 0;
        }
    });

}

function get_cap_key() {
    var key = $(".goods").find(".current").attr("data-src");
    return key;
}
function get_data_space(capital_key) {
    var capital_space_percent = 5;

    if (capital_key == "USDJPY") {
        capital_space_percent = 3;
    } else if (capital_key == "XAUUSD" || capital_key == "SILVER" || capital_key == "USOIL" || capital_key == "BTCCNY") {
        capital_space_percent = 2;
    } else if (capital_key == 'USDJPY' || capital_key == 'CADJPY' || capital_key == 'EURJPY' || capital_key == 'XAGUSD') {
        capital_space_percent = 3;
    }
    return capital_space_percent;
}

function get_r_second(){
    if(rsecond == 0){
        rsecond = Math.floor(Math.random() * 5  + 3);
    }
    return rsecond;
}

function countDown(endTime, dealtime) {
    /* dealtime是决胜时间 */
    //var endtime = new Date(endTime).getTime(); //取结束日期(毫秒值)
    var nowtime = new Date().getTime();
    var youtime = endTime - nowtime;
    var seconds = youtime / 1000;
    var CSecond = Math.floor(seconds % dealtime).toString(); //"%"是取余运算，可以理解为60进一后取余数，然后只要余数。
    var CMSecond = Math.floor(seconds * 100 % 100).toString();


    if (CSecond.length == 1) {
        CSecond = '0' + CSecond;
    }

    if (CMSecond.length == 1) {
        CMSecond = '0' + CMSecond;
    }

    if (CSecond == get_r_second() && (window.ed == 0 || window.ed == null)) {
        console.log("new_order_id:" + new_order_id);
        get_order(new_order_id);
    }
    if (CSecond == 3) {
        var captial = $(".sw_active a").attr("type");
        var dot_len = get_data_space(captial);
        var now_price_1 = parseFloat($("#now_price").text()).toFixed(dot_len);
        var diffrant = parseFloat(Math.abs(e_price - now_price_1)).toFixed(dot_len);
        var type = $("#time_diff a.changed").attr("type");
        var diff = type * 60;
        if ((order_dirt == 0 && now_price_1 <= new_order_price && !isNaN(diffrant) && diffrant <= fate && e_is && shifoukaishi !== 1) || (order_dirt == 1 && now_price_1 >= new_order_price && !isNaN(diffrant) && diffrant <= fate && e_is && shifoukaishi !== 1)) {
            end_datas = selectfrom(captial, e_price, diffrant, dot_len);
            console.log(1);
            // set_Kline_end(captial, e_price, diffrant, dot_len, order_dirt, 0);
            shifoukaishi = 1;
        } else {
            //clearInterval(window.param[captial+diff]);
        }
    }
    if (CSecond == 2) {
        var captial = $(".sw_active a").attr("type");
        var dot_len = get_data_space(captial);
        var now_price_1 = parseFloat($("#now_price").text()).toFixed(dot_len);
        var diffrant = parseFloat(Math.abs(e_price - now_price_1).toFixed(dot_len));
        var type = $("#time_diff a.changed").attr("type");
        var diff = type * 60;
        if (shifoukaishi > 0 && shifoukaishi !== 2) {
            console.log(2);
            set_Kline_end(captial, e_price, diffrant, dot_len, order_dirt, 2);
            shifoukaishi = 2;
        }
    }
    if (CSecond == 1) {
        var captial = $(".sw_active a").attr("type");
        var dot_len = get_data_space(captial);
        var now_price_1 = parseFloat($("#now_price").text()).toFixed(dot_len);
        var diffrant = parseFloat(Math.abs(e_price - now_price_1).toFixed(dot_len));
        var type = $("#time_diff a.changed").attr("type");
        var diff = type * 60;
        if (shifoukaishi > 0 && shifoukaishi == 2) {
            console.log(3);
            shifoukaishi = 0;
            //set_Kline_end(captial, e_price, diffrant, dot_len, order_dirt, 1);
        }
    }
    if (CSecond <= 0) {
        // alert("csec=0");
        $(".sec").text('00');
        $("#js-sec-text").html( 0 );
        var e = Math.round( 0/dealtime * 570.846 );
        document.getElementById("js-sec-circle").style.strokeDashoffset = e-570.846;



        clearInterval(timer_countDown);
        clearInterval(timer_countDown);
        clearInterval(timer_countDown);
        //get_order(new_order_id);
        //设置倒计时的地方
        set_data(ed);
        cishu = 0;
        //clearInterval(end_time_Interval);
        //setTimeout(function () {drawKline_end(getCapitalTypeById("sw_active"), getDiffById("time_diff"), "svgId", "", "deal_value");}, 2000);
    }
    else {
        $("#js-sec-text").html(CSecond);
        var e = Math.round( CSecond/dealtime * 570.846 );
        document.getElementById("js-sec-circle").style.strokeDashoffset = e-570.846;
        //alert( document.getElementById("js-sec-circle").getTotalLength() );

        $(".sec").text(CSecond);
    }
}

/*加载首页订单列表里的订单    持仓订单*/
function load_now2(num, PAGESIZE, isnull,url) {
    $.ajax({
        type: "POST",
        url: ROOT + url,
        data: "page=" + num + "&pagesize=" + PAGESIZE ,
        datatype: 'JSON',
        success: function (response) {
            //alert( response );
            for( var i in response )
            {
                //alert( i+"\n"+response[i] );
            }
            //alert( response.list.length );
            $(".more-btn").addClass("hide");
            $("#now_list").removeClass("hide");
            $("#now_list").empty();
            if (response.status == 1) {
                $("#now_list").append('<dl><dt>下单时间</dt><dd>资产类型</dd><dd>方向</dd><dd>执行价格</dd><dd>当前价格</dd><dd>定金</dd></tr>');
                $.each(response.list, function (key, value) {
                    $("#now_list").append('<dl onclick="get_history(\'' + value.id + '\',this)" id="' + value.id + '"><dt>' + value.trade_time + '</dt><dd>' + value.option_key + '</dd><dd>' + value.trade_direction + '</dd><dd>' + value.trade_point + '</dd><dd>' + value.trade_point + '</dd><dd>' + value.trade_amount + '</dd></dl>');
                    $(".come-txt").text("");
                });
            } else {
                if (num == 1) {
                    $("#now_list").addClass("hide");
                    $(".come-txt").text("当前没有任何记录");
                    $(".com-empty").removeClass("hide");
                }
                return false;
            }
        },
        error: function () {
        },
        complete: function () {
            //hideLoading()
        }
        //  "json");
    });
}


/*加载首页订单列表里的订单    最近的订单*/
function load_now(num, PAGESIZE, isnull,url) {
    $.ajax({
        type: "POST",
        url: ROOT + url,
        data: "page=" + num + "&pagesize=" + PAGESIZE,
        datatype: 'JSON',
        success: function (response) {
            //alert( response );
            $(".more-btn").addClass("hide");
            $("#trrecord").removeClass("hide");
            $("#trrecord").empty();
            if (response.status == 1) {
                $("#trrecord").append('<dl><dt>下单时间</dt><dd>资产类型</dd><dd>买入方向</dd><dd>订单状态</dd></tr>');
                $.each(response.list, function (key, value) {
                    $("#trrecord").append('<dl onclick="get_history(\'' + value.id + '\',this)" id="' + value.id + '"><dt>' + value.trade_time + '</dt><dd>' + value.option_key + '</dd><dd>' + value.trade_direction + '</dd><dd>' + value.is_settle + '</dd></dl>');
                    $(".come-txt").text("");
                });
            } else {
                if (num == 1) {
                    $("#trrecord").addClass("hide");
                    $(".come-txt").text("当前没有任何记录");
                    $(".com-empty").removeClass("hide");
                }
                return false;
            }
        },
        error: function () {
        },
        complete: function () {
            //hideLoading()
        }
        //  "json");
    });
}

function buycomplete(){
    $.ajax({
        type: "POST",
        url: ROOT + "/Wap/Trading/get_now_money",
        datatype: 'JSON',
        success: function (response) {

            $("#_balance").html(response);
        },
        error: function () {
        },
        complete: function () {
            //hideLoading()
        }
        //  "json");
    });
}
setInterval(function(){
    getchangerate();
},3000)

setInterval(function(){
    getBtcBuyPri();
},1000)


function getchangerate(){
    $.ajax({
        type: "POST",
        url: ROOT + "/Wap/Trading/getchangerate",
        datatype: 'JSON',
        success: function (response) {
            if( response != null || response != "" ){
                changerate = response;
            }
        },
        error: function () {
        },
        complete: function () {
            //hideLoading()
        }
        //  "json");
    });
}
/*倒计时结束时会调用这个函数*/
function get_order(id) {
    var type = $("#time_diff li.current").attr("data-src");
    var dealva = $("#flow_span_value1").find('font').html();//当前价格

    jQuery.ajax({
        type: 'post',
        url: ROOT + "/Wap/Trading/get_history_ajax",
        data: "id=" + id + "&type=" + type + '&deal_value=' + dealva,
        dataType: 'JSON',
        // dataType: 'text',
        async: true,
        timeout: 2000,
        error: function (data) {
            get_order(id);
            $("#flow_span_value2").hide();
            /* showLoading('网络错误，请在历史订单中查看！',2000);
             pop_Close();*/
            return 0;
        },
        success: function (data_t) {
            json_data = eval(data_t);
            if (json_data['status'] == '1') {
                ed = json_data;             // new add
                window.ed.id = id;
                window.ed.type = type;
                console.log(json_data);
                if(json_data["is_win"] == 1){
                    console.log("赢:" + parseFloat(json_data['profit']).toFixed(2));
                }
                else if(json_data["is_win"] == 2){
                    console.log("平:" + parseFloat(json_data['profit']).toFixed(2));
                }
                else{
                    console.log("亏:" + parseFloat(json_data['profit']).toFixed(2));

                }

            } else {
                get_order(id);
            }
            return 0;
        }
    });
}


function set_data(json_data) {
    $("#flow_span_value2").hide();
    $("#flow_span_value2").hide();
    //var dot_len = get_data_space(json_data['option_key']);
    //$("#dangqian").html('当前价格：<i id="flow_span_value_d">' + parseFloat(json_data['settle_point']).toFixed(2) + '</i>');
    $("#flow_span_value1").html('<font>' + parseFloat(json_data['settle_point']).toFixed(2) + '</font>');
    $("#flow_span_value3").show();
    if (json_data['is_win'] == '1') {
        $("#js_alert_result").html("盈+"+parseFloat(json_data['profit']).toFixed(2));
        $("#js_alert_result").removeClass("none").addClass("red");
        $("#js-alert-box").removeClass("showblock");
    } else if (json_data['is_win'] == '2') {
        $("#js_alert_result").html("平"+parseFloat(json_data['profit']).toFixed(2));
        $("#js_alert_result").removeClass("none").addClass("gray");
        $("#js-alert-box").removeClass("showblock");
    } else {
        $("#js_alert_result").html("亏-"+parseFloat(json_data['profit']).toFixed(2));
        $("#js_alert_result").removeClass("none").addClass("green");
        $("#js-alert-box").removeClass("showblock");
    }


    json_data = null;
    window.ed = null;
    rsecond = 0;
}
/*更新预测结果*/
setInterval(function (){
    // alert(  $("#flow_span_value_d").val() );
    // alert(  $("#flow_span_value_d").innerHTML );
    // alert(  $("#flow_span_value_d").html() );flow_span_value1
    var e = $("#flow_span_value1").find("font");

    chg_p = parseFloat($("#flow_span_value1").find("font").html());
    cur_p = parseFloat($("#buy_price").html());
    // alert( chg_p+",,"+ cur_p+",,,"+$("#_buy_type").val());
    if(cur_p<chg_p&&$("#_buy_type").val()=='-1'){
        $('#flow_span_value2').html('<font color=green>亏</font>');
    }

    else if(cur_p>chg_p&&$("#_buy_type").val()=='-1') {
        $('#flow_span_value2').html('<font color=red>盈</font>');
    }
    else if(cur_p<chg_p&&$("#_buy_type").val()=='1') {
        $('#flow_span_value2').html('<font color=red>盈</font>');
    }
    else if(cur_p>chg_p&&$("#_buy_type").val()=='1') {
        $('#flow_span_value2').html('<font color=green>亏</font>');
    }else{
        $('#flow_span_value2').html('平局');
    }

},1000);



var curMin= 0;
var curHour = 0;
var ready=false;
var date = [];
var dataK = [];
var dataL = [];
var noPop=false;
var showType ='0';
var myChart = echarts.init( document.getElementById("container") );
myChart.showLoading({text:'',textColor:'#9b9b9b',color:'#444',maskColor:'rgba(0, 0, 0, 0.2)'});
function getDate(){
    D = new Date();
    curMin= D.getMinutes();
    curHour = D.getHours();
    curMin = (curMin<10)?'0'+curMin:curMin;
    curHour = (curHour<10)?'0'+curHour:curHour;
}

setTimeout(function(){
    IfDrawminmin();
},500);

function IfDrawminmin(){
    if( showType == '0' ){
        getbtcminmin();
        //
        //setInterval(function(){
        //    getgoldminmin();
        //    getbtcminmin();
        //},500);

    }
}

function getbtcminmin(){
    $.ajax({
        type: "GET",
        url: "/Wap/Trading/btcminmindata",
        datatype: 'JSON',
        success: function (response) {
            console.log( response );
            processDataChild(response,"minmin")
        },
        error: function () {
        },
        complete: function () {
        }
    });
}

function getgoldminmin(){
    $.ajax({
        type: "GET",
        url: "/Wap/Trading/web_get_silver2",
        datatype: 'JSON',
        success: function (response) {
            // console.log( response );
            processDataChild(response,"minmin")
        },
        error: function () {
        },
        complete: function () {
        }
    });
}


function processDataChild(dat,type) {
    var newdate = new Date();
    ready=false;
    getDate();
    date.splice(0,date.length);
    dataL.splice(0,dataL.length);
    //if( showType == '0' ){
    if( type == "minmin" ){
        /*分时图
         * time  value _min _max
         * value有200个价格数据
         * */
        myChart.setOption(optionL);
        $("#_min").html(dat._min);
        $("#_max").html(dat._max);
        if(typeof(dat.time)=='object') { for(k in dat.time) date.push(dat.time[k]); };
        if(typeof(dat.value)=='object') { for(k in dat.time) dataL.push(dat.value[k]); };
        setL(dataL[dataL.length-1]);
    }else {
        if( showType == '0' )
        {
            return;
        }
        if (dat.data.length > 2) {
            /*
             30M按钮，K线图时间间隔30秒    15
             15按钮，K线图时间间隔15秒     15
             5M按钮，K线图时间剪个5秒      15
             1M按钮，K线图时间间隔1秒      15组数据
             * */
            dataK.splice(0, dataK.length);
            myChart.setOption(optionK);

            if (dat.data.length > 2) {
                if (dat.data != null) dat.data.forEach(function (v, i, o) {
                    newdate.setTime(v[0]);
                    var minutes = newdate.getMinutes();
                    if( minutes < 10 )
                    {
                         minutes = '0'+minutes;                
                    }
                    date.push(newdate.getHours() + ":" + minutes );
                    // a = [v.open, v.close, v.lowest, v.hightest];
                    a = [v[1], v[4], v[3], v[2]];
                    dataK.push(a);
                });
                date.push(curHour + ":" + curMin);
                a[0] = a[1];
                dataK.push(a);
                setK(dataK[dataK.length - 1][3]);
            }
        }
    }
    myChart.hideLoading();
    ready=true;
}
function processData(dat,type){
    processDataChild( dat,type);
}



function getBtcBuyPri(){
    $.ajax({
        type: "GET",
        //url: "https://data.btcchina.com/data/ticker?market=btccny",
        //url: "https://www.okcoin.cn/api/v1/ticker.do?symbol=btc_cny",
        url: "/Wap/Trading/getCurBtcPrice",
        datatype: 'JSON',
        success: function (response) {
              if( response['ticker'] )
            {

                if( response['ticker']['buy'] )
                {
                    var newdat = new Object();
                    newdat._code = "BTbtccny";

                    newdat._curprice = parseFloat(response['ticker']['buy'])+parseFloat(Math.random().toFixed(2));
                    //newdat._curprice = parseFloat(response['ticker']['buy']);

                    newdat._curprice = (newdat._curprice).toFixed(2);
                    var date = new Date();
                    date.setTime( response['ticker']['date']*1000 );
                    newdat._time = date.getHours()+":"+ date.getMinutes();
                    addStockChild( newdat );
                }
            }

        },
        error: function () {
        },
        complete: function () {
        }
    });

    $.ajax({
        type: "GET",
        url: "/Wap/Trading/getCurGoldPrice",
        datatype: 'text',
        success: function (response) {
            var res = (parseFloat(response)+parseFloat((Math.random()/12).toFixed(2))).toFixed(2);
            //var res = parseFloat(response).toFixed(2);
            var newdat = new Object();
            newdat._code = "NECLA0";
            newdat._curprice = res;
            var date = new Date();

            var minutes = date.getMinutes();
            if( minutes < 10 )
            {
                 minutes = '0'+minutes;                
            }

            newdat._time = date.getHours()+":"+ minutes;
            
                    //console.log( newdat );
            addStockChild( newdat );

        },
        error: function () {
        },
        complete: function () {
        }
    });



}

function addStockChild(dat) {
    if(ready==false) return true;
    oldValue = parseFloat($("#"+dat._code).html());if(oldValue=='NaN') oldValue=0;
    className = (oldValue>dat._curprice)?'green_d':'red_z';
    classNameColor = (oldValue>dat._curprice)?'green':'red';
    $("#"+dat._code).removeClass().addClass(classNameColor).html(dat._curprice+"元<i></i>").children("i").removeClass().addClass(className);

    if( $("#cur_show_good").val() ==  dat._code )
    {
        $("#flow_span_value").html('<font color='+classNameColor+'>' + dat._curprice + '</font>');
        $("#flow_span_value1").html('<font color='+classNameColor+'>' + dat._curprice + '</font>');
    }


    if(("#_buy_cur_price").length>0 && $("#cur_show_good").val()==dat._code) $("#_buy_cur_price").removeClass().addClass( className ).html(dat._curprice);
    //对应插入data
    if(dat._code==$("#cur_show_good").val()){
        if(dat._curprice>parseFloat($("#_max").html())) $("#_max").html(dat._curprice);
        if(dat._curprice<parseFloat($("#_min").html())) $("#_min").html(dat._curprice);
        curr_time = dat._time.substr(11);
        last_time = date[date.length-1];
        if($(".kxt_btn").find('.current').data('src')=='0') {
            /*分时图的数据自己造出来*/
            if(typeof(last_time)!='undefined' && last_time.substring(0,5)!=curr_time.substring(0,5)) {
                date.push(curr_time.substring(0,5));
                dataL.push(dat._curprice);
                //_Toast(dat._curprice);
                date.shift();
                dataL.shift();
            }
            setL(dat._curprice);

        }else{
            // K
            //console.log( dataK[20] );
            last_data = dataK[dataK.length-1];
            // last_data = dataK[20];
            cp = parseFloat(dat._curprice);
            if(last_data==undefined) return;
            sp = last_data[1];
            last_data = [ last_data[0], dat._curprice , cp<parseFloat(last_data[2])?cp:last_data[2], cp>parseFloat(last_data[3])?cp:last_data[3] ];
            //console.log(dat._time.substr(14,2)+"|"+curMin+"|"+showType+"|"+(parseInt(curMin)+parseInt(showType)));
            if(parseInt(dat._time.substr(14,2))!=(parseInt(curMin)+parseInt(showType))){
               dataK.pop();
            }else{
               getDate();
               date.push(curHour+":"+curMin);
               last_data[0] = last_data[1];
            }
            dataK.push(last_data);
            setK(last_data[1]);

        }
    }
}

function addStock(dat,type){
    //if(dat._code == "NECLA0"){
    if(false){
        dat._open = (Number(dat._open)*Number(changerate)).toFixed(2);
        dat._hightest = (Number(dat._hightest)*Number(changerate)).toFixed(2);
        dat._lowest = (Number(dat._lowest)*Number(changerate)).toFixed(2);
        dat._curprice = (Number(dat._curprice)*Number(changerate)).toFixed(2);
        addStockChild(dat);
    }else{

        console.log(dat);
        //addStockChild(newdat,type);
    }
}

function changeK(v){
    myChart.showLoading({text:'',textColor:'#9b9b9b',color:'#444',maskColor:'rgba(0, 0, 0, 0.2)'});
    showType=v;
    if(v==0)myChart.setOption(optionL);
    else myChart.setOption(optionK);
    myChart.hideLoading();
}
function recharge(d){ if(d.status==1) document.location.href=d.url;else popPerfect();}
function sign(d){ if(d.status==1){$("#_sign_dt").remove();_Toast('今天簽到完成了！');}else popLogin(1,'/Index',false);}
function buyStock(t){
    _Tip('',99999);
    $.get('/Product/prepareOrder',{buy_type:t,buy_time:$("#buy_time").val(),product:$("#cur_show_good").val()},function(data){
        noPop=true;
        lclose();
        if(data.error=='-100') popLogin();
        else{
            layer.open({type:1,shadeClose:false,style:'background:none;width:99%',content:data.content,end:function(){noPop=false;} });
            if(data.status==1) {
                $(".buys_money ul li").on('touchend',function(){
                    newPrice =  parseInt($(this).data('src'));
                    $(this).siblings().removeClass();$(this).addClass('current'); $("#buy_price").val(newPrice);$(".mr_money").html(newPrice);
                    $(".yj_money").html( (newPrice-newPrice*parseFloat($("#tax").val())/100)*(1+parseFloat(data.rate)) );
                });
                $(".coupon dd").on('touchend',function(){ $(this).siblings().removeClass();$(this).addClass('current'); $("#coupon").val($(this).data('src'));});
                $("#_buy_cur_price").html( $("#"+$("#cur_show_good").val()).html() );
                $(".yj_money").html(  (parseInt($("#buy_price").val())-parseFloat($("#tax").val())) * (1+parseFloat(data.rate)) );
            }
        }
    },'json');
}
optionL = {
    backgroundColor: '#000000',
    gridIndex:0,
    grid: {top:13,bottom:50,right:3,left:3,containLabel:true},
    tooltip: {trigger: 'axis',
        formatter:function(params){
            return '<div style="background:#111111;' +
                'border-radius:5px;padding:3px 3px 3px 3px;color:#eeeeee">时间：'+params[0].axisValue+'<br/>价格：'+params[0].value+'</div>';
        }
    },

    legend:{show:false,padding:0,top:0},
    title:{show:false},
    xAxis:{type: 'category',boundaryGap:[0,0],axisTick: {show: true,lineStyle:{color:'#9b9b9b'} },
        axisLabel:{textStyle:{color:'#9b9b9b'},formatter:function(v,index){return v.substring(0,5);},inside:false },
        splitLine:{show:false ,lineStyle:{color:'#9b9b9b',type:'dashed',opacity:0.2} },
        data:[]
    },

    yAxis:{type: 'value',boundaryGap: [0.2, 0.2],
        axisLabel:{show:false,inside:true,textStyle:{color:'#9b9b9b',fontSize:8},formatter:function (value, index) {
            return value.toFixed(2);
        } },
        axisTick: {show:false,inside:true,lineStyle:{color:'#9b9b9b'} },
        splitLine: {show:true,lineStyle:{color:'#9b9b9b',type:'solid',opacity:0.2} },
        scale:true,
        zlevel:10
    },
    series: [{
        name:'分时图',type:'line',smooth:true,symbol:'none',
        itemStyle:{
            //normal:{color:'#f1d220',lineStyle:{width:1,opacity:0.4}}
            normal:{color:'#fbd073',lineStyle:{width:1,opacity:1.4}}
        },
        areaStyle: {
            normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: '#fbd073'
                }, {
                    offset: 1,
                    color: '#fbd073'
                }])
            }
        },
        data:[]
    }]
};
optionK = {
    backgroundColor: '#000000',
    gridIndex:0,
    //grid: {top:13,bottom:50,right:10,left:-5,containLabel: true},
    grid: {top:13,bottom:50,right:3,left:3,containLabel: true},
    tooltip: {trigger: 'axis',
        formatter: function (params) {
            var res =  params[0].name;
            res += '<br/> 开盘 : ' + params[0].value[1] + '<br/>最高 : ' + params[0].value[4];
            res += '<br/> 收盘 : ' + params[0].value[2] + '<br/>最低 : ' + params[0].value[3];
            return res;
        }
    },
    legend:{show:false,padding:0,top:0},
    title: {show:false },
    xAxis: {
        type: 'category',
        scale: true,boundaryGap: true,
        axisTick: {show: true,lineStyle:{color:'#9b9b9b'} },
        axisLabel:{inside:false,textStyle:{color:'#9b9b9b'} },
        splitLine: {show:false ,lineStyle:{color:'#9b9b9b',type:'dashed',opacity:0.2} },
        data:[]
    },
    yAxis: {
        axisLabel:{show:false,inside:true,textStyle:{color:'#c0c0c0',opacity:0.2},formatter: function (value, index) {
            return value.toFixed(2);
        } },
        axisTick: {show:false,inside:true,lineStyle:{color:'#9b9b9b'} },
        splitLine: {show:true ,lineStyle:{color:'#9b9b9b',type:'solid',opacity:0.2} },
        scale:true,
        zlevel:10
    },
    series: [
        { name:'日K',
            type:'candlestick',
            data:[],
            itemStyle:{ normal:{color:'red',color0:'green'} },
        }
    ]
};

function setL(lv){
    myChart.setOption(
        {
            xAxis:{data:date},
            series:[{name:'分时图',data:dataL,
                markLine:{label:{normal:{show:true}},symbol:['none','none'],data:[{name:'curp',yAxis:lv,label:{
                    normal:{position:'middle',formatter:function(p){return parseFloat(p.value).toFixed(2);}}}}]},
                itemStyle:{
                    normal:{color:'#ffe337',lineStyle:{width:2,opacity:0.6}}
                },
                areaStyle: {
                    normal:{
                        color: {type: 'linear',x: 0, y: 0,x2: 0,y2: 1,
                            colorStops: [{offset:0,color:'#d8b631'},{offset:1,color:'#fbd073'}],
                            globalCoord: false
                        },
                        opacity:0.4
                    }
                },
                smooth:true,
            }]});
}
function setK(lv){
    myChart.setOption({
        xAxis: {data: date},
        series: [{name: '日K',data: dataK,markLine: {symbol: ['none','none'],data:[{name: 'curp',yAxis:lv,label:{
            normal:{position:'middle',formatter:function(p){return parseFloat(p.value).toFixed(2);}}}}]},
            markPoint:{data:[{name:'当前',coord:[date[date.length-1],parseFloat(lv).toFixed(2)],label:{normal:{offset:[-10,0],textStyle:{fontSize:6,color:'#ffff00'}}} }]}
        }]
    });
}

function random(){
    var c = Math.round(Math.random()*99+1);
    return c;
}

function addItem(dat){

    if( dat.buy == "買跌" )
    {
        dat.buy = "买跌"
    }else if( dat.buy == "買漲" )
    {
        dat.buy = "买涨"
    }

    if( dat.name == "比特幣")
    {
        dat.name = "比特币";
    }


    if( dat.name == "美黃金" )
    {
        return;
    }

    var wi = random();


    $('<dl><dt>'+dat.time+'</dt><dd>'
        +dat.name+'</dd><dd class="'
        +(dat.buy_state==1?'red':'green')+'">'
        +dat.buy+'</dd><dd><b>'
        +dat.price+'</b><span><i style="display: block;height: 100%;width:'+wi+'%" class="'
        +(dat.buy_state==1?'red_bg':'green_bg')+
        '"></i></span></dd></dl>').insertAfter($("#index_data_0 dl").eq(0) );
    max_length = $("#index_data_0 dl").length;
    if(max_length > 21 ){
        $("#index_data_0 dl").eq(max_length-1).remove();
    }
}

d = new Date(Date.parse($("#_inputdate").val().replace(/-/g, "/")));
cd = d.getTime();
/*
 setInterval(function (){
 cd+=1000;
 d = new Date(cd);
 _hours = d.getHours(),_minutes=d.getMinutes(),_second=d.getSeconds();_second = _second<10?('0'+_second):_second;
 d = (_hours<10?('0'+_hours):_hours) + '：' + (_minutes<10?('0'+_minutes):_minutes) + '：' + _second;
 $("#_time").html(d);
 $("[id*=_cdown]").each(function(i,v){
 t = parseInt($(this).html());
 if(t--<=0) {
 reposition();
 }else{
 vt=(t<10)?'0'+t:t;
 $(this).html(vt);
 }});
 if($("#_cdown2").length>0 && !isNaN(parseInt($("#_cdown2").html()))){
 c2 = parseInt($("#_cdown2").html());
 chg_p = parseFloat($("#_buy_cur_price").html());
 cur_p = parseFloat($("#_buy_price").html());
 if(cur_p<chg_p&&$("#_buy_type").val()=='-1') $("#_re2").removeClass().addClass('green').html('虧');
 else if(cur_p>chg_p&&$("#_buy_type").val()=='-1') $("#_re2").removeClass().addClass('red').html('盈');
 else if(cur_p<chg_p&&$("#_buy_type").val()=='1') $("#_re2").removeClass().addClass('red').html('盈');
 else if(cur_p>chg_p&&$("#_buy_type").val()=='1') $("#_re2").removeClass().addClass('green').html('虧');
 else $("#_re2").removeClass().html('平');
 $("#_cdown2").html((c2<10)?'0'+c2:c2);
 if(c2--<=0){
 $("#_rh").html('&nbsp;');
 $("#_result").html('結算中，請稍候');
 showResult($("#_orderno").val());
 }else if(c2==9 && !$("#_cdown2").hasClass('heart')) {
 $("#_cdown2").addClass("heart");
 }
 }
 },1000);*/
//提交新订单
function doSubmitPrepareOrder(){
    noPop=true;
    $("#buy_point").val($("#_buy_cur_price").html());
    $.post('/Order/create',$("#prepare_order").serialize(),function(data){
        layer.closeAll();
        if(data.status==1){
            $("#_balance").html(data.balance);
            if($("#buy_time").val()==60) layer.open({type:1,style:'background:none;width:99%',shadeClose:false,content:data.content});
            else _Tip('下單成功，請在持倉訂單中查看。', 4);
            //更新自己的持仓状态
            reposition();
        }else{
            layer.open({type:1,style:'background:none;width:100%;',content:data.error,end:function(){noPop=false;}});
        }
    },'json');
}
function reposition(){
    $.post('/Order/position',function(data){
        if(data.content0.length>1) $("#_dot").addClass('dot');else $("#_dot").removeClass();
        $(".index_data").eq(1).html(data.content0);
        $(".index_data").eq(2).html(data.content1);
        $("#_balance").html(data.balance);
        $("#hold_0,#hold_1,#hold_2").hide();
        if(typeof(data.hold)=='object') {
            for(i=0;i<data.hold.length;i++) $("#hold_"+data.hold[i].p).show().html(data.hold[i].v);
        }
    },'json');
}
/*增加新的list图标中的数据*/
function showResult(orderno){
    setTimeout(function(){
        $.post('/Order/checkOrder',{orderno:orderno},function(data){
            if(data.balance==false) lclose();
            /*else if(data.balance.indexOf('B')==0) {p=data.balance.split('_');$("#_result").html(p[1]);$("#_result_p").html('當前<em>持平</em>').addClass('_result_p');}
             else $("#_result").html((parseFloat(data.balance)>0)?('+'+data.balance):data.balance);
             if(data.balance>0) {$("#_result_p").html('當前<em class="red">盈</em>').addClass('_result_p');}
             else if(data.balance<0) {$("#_result_p").html('當前<em class="green">虧</em>').addClass('_result_p');}
             reposition();
             if(typeof(data.orderRow)!='undefined') {
             layer.closeAll();
             direction = '買'+(data.orderRow.buy_direct==1?'漲':'跌');
             if(data.orderRow.complete_fee>0) win(data.orderRow.buy_product_name,data.orderRow.complete_fee,data.orderRow.tax_total_fee,data.orderRow.buy_price_total_price,direction);
             else loss(data.orderRow.buy_product_name,data.orderRow.buy_price_total_fee,direction);
             }*/
            if(data.balance.indexOf('B')==0) {p=data.balance.split('_');$("#_result").html(p[1]);$("#_result_p").html('當前<em>持平</em>').addClass('_result_p');}
            else{
                layer.closeAll();
                direction = '买'+(data.orderRow.buy_direct==1?'涨':'跌');
                if(data.orderRow.complete_fee>0) win(data.orderRow.buy_product_name,data.orderRow.complete_fee,data.orderRow.tax_total_fee,data.orderRow.buy_price_total_fee,direction);
                else loss(data.orderRow.buy_product_name,data.orderRow.buy_price_total_fee,direction);
            }
        },'json');
    }, 1200);
}
function rePop(oid){
    $.post('/Order/rPopup',{orderno:oid},function(data){if(data.status==1){_Err(data.content);
        $("#cur_show_good").val(data.buy_product);$(".goods ul li").each(function(i){ if($(this).data('src')==data.buy_product)$(this).addClass('current');else $(this).removeClass(); });
    }else _Toast(data.error);},'json');
}
//新手引导操作
function novice(){
    $("nav").animate({"opacity":"0.1"});
    function append_con_one(){
        $("#maskIn1").css({"display":"block"}).siblings("div").css({"display":"none"});
        //显示高亮
        $("section .goods").siblings().animate({"opacity":"0.1"});
        //从第一步跳转到第二步
        $("#maskIn1 .on_c_next").click(function(){
            append_con_two();
        });

    }
    function append_con_two(){
        $(window).scrollTop(0);
        $("#maskIn2").css({"display":"block"}).siblings("div").css({"display":"none"});
        $("section .game_time").animate({"opacity":"1"}).siblings().animate({"opacity":"0.1"});
        $(".swiper-container").siblings().animate({"opacity":"0.1"});
        $(".swiper-container").children("i").animate({"opacity":"0.1"});
        //从第二步返回第一步
        $("#maskIn2 .mask_true").click(function(){
            append_con_one();
        });
        $("#maskIn2 .on_c_next").click(function(){
            append_con_three();
        })
    }
    function append_con_three(){
        $(window).scrollTop(150);
        $("#maskIn3").css({"display":"block"}).siblings("div").css({"display":"none"});
        $("section .game_time").animate({"opacity":"1"}).siblings().animate({"opacity":"0.1"});
        $(".swiper-container").siblings().animate({"opacity":"0.1"});
        $(".swiper-container").children("div").animate({"opacity":"0.1"});
        $(".kxt").animate({"opacity":"1"});
        $("#maskIn3 .mask_true").click(function(){
            append_con_two();
        });
        $("#maskIn3 .on_c_next").click(function(){
            append_con_four();
        })

    }
    function append_con_four(){
        $(window).scrollTop(0);
        $("#maskIn4").css({"display":"block"}).siblings("div").css({"display":"none"});
        $("section").children().animate({"opacity":"0.1"});
        $("#maskIn4 .mask_true").click(function(){
            append_con_three();
        });
        $("#maskIn4 .on_c_next").click(function(){
            append_con_five();
        })


    }
    function append_con_five(){
        $(window).scrollTop(0);
        $("#maskIn5").css({"display":"block"}).siblings("div").css({"display":"none"});
        $("section").children().animate({"opacity":"0.1"});

        $("#maskIn5 .on_c_next").click(function(){
            $(this).parent("div").css({"display":"none"});
            $("#novice").animate({"opacity":"1"});
            $("section>*").animate({"opacity":"1"});
            $(".swiper-container").children().animate({"opacity":"1"});
            $(".game_time").children().animate({"opacity":"1"});
            $("nav").animate({"opacity":"1"});
        })

    }
    var window_h = $(window).height();
    $("body>div").height(window_h);
    $("#novice").animate({"opacity":"0.1"});
    //执行第一个动画
    append_con_one();
    $(".mask_guan").click(function(){
        $(this).parent("div").css({"display":"none"});
        $("#novice").animate({"opacity":"1"});
        $("section>*").animate({"opacity":"1"});
        $(".swiper-container").children().animate({"opacity":"1"});
        $(".game_time").children().animate({"opacity":"1"});
        $("nav").animate({"opacity":"1"});
    });

}
$("#novice").click(function(){
    novice();
});

function win(data_goods,money,service_charge,buy_amount,direction){
    var window_h = $(window).height();
    var o_div = $("<div class='mask_profit'></div>");
    o_div.height(window_h);
    $("body").append(o_div);
    $(".mask_profit").css({"background":"rgba(0,0,0,0.8)","width":"100%","position":"fixed","left":"0","top":"0","z-index":"600"});
    var content = $("<div class='profit'>\
						<i class='not_win_colos'></i>\
							<dl>\
							<dt>盈利"+money+"元！</dt>\
						<dd>合约："+data_goods+" <span style='color: #E35C58;margin-left: 4%;'>"+buy_amount+direction+"</span></dd>\
						<dd>手续费："+service_charge+"元</dd>\
						</dl>\
						<a href='javascript:;' class='jixu'>继续下单 &gt;&gt;</a>\
					</div>");
    o_div.append(content);
    $(".not_win_colos").click(function(){
        console.log(1);
        $(".mask_profit").remove();
    });
    $(".profit a").click(function(){
        console.log(1);
        $(".mask_profit").remove();
    });
}
function loss(data_goods,buy_amount,direction){
    var window_h = $(window).height();
    var o_div = $("<div class='mask_profit'></div>");
    o_div.height(window_h);
    $("body").append(o_div);
    $(".mask_profit").css({"background":"rgba(0,0,0,0.8)","width":"100%","position":"fixed","left":"0","top":"0","z-index":"600"});
    var content = $('<div class="profit profit_not">\
						<i class="not_win_colos"></i>\
							<dl>\
							<dt style="margin-bottom: 5%;">很遗憾<br>继续努力!</dt>\
						<dd><span class="red" style="font-size: 0.8125rem;">'+data_goods+buy_amount+direction+'</span></dd>\
						</dl>\
						<a href="javascript:;" class="fanhui">确认返回 &gt;&gt;</a>\
					</div>');
    o_div.append(content);
    $(".not_win_colos").click(function(){
        console.log(1);
        $(".mask_profit").remove();
    });
    $(".profit a").click(function(){
        console.log(1);
        $(".mask_profit").remove();
    });
}


